package com.backend.demo.action;

import java.io.File;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.interceptor.RequestAware;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

/**
 * 单个文件上传Action
 * @author Administrator
 *
 */
@ParentPackage("user")
@Namespace("/jspView")
@Controller
public class UploadAction extends ActionSupport implements RequestAware{
	
	private static final long serialVersionUID = 1L;
	private Map<String,Object> request;
	private File profileimg; //上传的文件
    private String profileimgFileName; //文件名称
    private String profileimgContentType; //文件类型
    
    public File getProfileimg() {
		return profileimg;
	}
	public void setProfileimg(File profileimg) {
		this.profileimg = profileimg;
	}
	
    public String getProfileimgFileName() {
		return profileimgFileName;
	}
	public void setProfileimgFileName(String profileimgFileName) {
		this.profileimgFileName = profileimgFileName;
	}
	public String getProfileimgContentType() {
		return profileimgContentType;
	}
	public void setProfileimgContentType(String profileimgContentType) {
		this.profileimgContentType = profileimgContentType;
	}
	
	@Action(value="upload",results={@Result(name=SUCCESS,location="/jspView/users/uploadImg.jsp"),@Result(name=ERROR,location="/jspView/user/editUser.jsp")})
    public String execute() throws Exception {
        String realpath = ServletActionContext.getServletContext().getRealPath("/upload");
        if (profileimg != null) {
            File savefile = new File(new File(realpath), profileimgFileName);
            if (!savefile.getParentFile().exists())
                savefile.getParentFile().mkdirs();
            FileUtils.copyFile(profileimg, savefile);
            ActionContext.getContext().put("message", "文件上传成功");
            request.put("profileimgFileName", profileimgFileName);
            return SUCCESS;
        }
        return ERROR;
    }
	
	@Override
	public void setRequest(Map<String, Object> request) {
		this.request = request;
	}
}
